<template>
  <div class="marking-container">
    <el-card class="marking-header">
      <div class="header-title">
        <h2>试卷批阅</h2>
        <el-tag v-if="markingStrategy === 1" type="primary">按整张试卷批阅</el-tag>
        <el-tag v-else-if="markingStrategy === 2" type="success">按单道大题批阅</el-tag>
      </div>
      
      <div class="header-info">
        <div class="exam-info">
          <p><strong>考试名称：</strong>{{ examInfo.name }}</p>
          <p><strong>考试时间：</strong>{{ examInfo.startTime }} - {{ examInfo.endTime }}</p>
        </div>
        <div class="marking-actions">
          <el-select v-model="markingStrategy" placeholder="选择批阅策略" @change="handleStrategyChange">
            <el-option :value="1" label="按整张试卷批阅"></el-option>
            <el-option :value="2" label="按单道大题批阅"></el-option>
          </el-select>
          <el-button type="primary" @click="saveMarking">保存批阅结果</el-button>
        </div>
      </div>
    </el-card>

    <!-- 按整张试卷批阅模式 -->
    <div v-if="markingStrategy === 1" class="full-paper-mode">
      <el-card class="student-info-card">
        <template #header>
          <div class="student-card-header">
            <span>学生信息</span>
            <div>
              <el-button size="small" @click="prevPaper">上一份</el-button>
              <span class="paper-counter">{{ currentPaperIndex + 1 }}/{{ totalPapers }}</span>
              <el-button size="small" @click="nextPaper">下一份</el-button>
            </div>
          </div>
        </template>
        <div class="student-details">
          <p><strong>姓名：</strong>{{ currentStudent.name }}</p>
          <p><strong>学号：</strong>{{ currentStudent.studentId }}</p>
          <p><strong>班级：</strong>{{ currentStudent.className }}</p>
          <p><strong>提交时间：</strong>{{ currentStudent.submitTime }}</p>
        </div>
      </el-card>

      <el-card class="paper-content">
        <el-collapse v-model="activeQuestionGroups">
          <el-collapse-item v-for="(group, groupIndex) in paperContent" :key="groupIndex" :title="group.title" :name="groupIndex">
            <div v-for="(question, qIndex) in group.questions" :key="qIndex" class="question-item">
              <div class="question-header">
                <span class="question-title">{{ question.questionNum }}. {{ question.title }}</span>
                <span class="question-score">({{ question.score }}分)</span>
              </div>
              <div class="question-content">
                <div v-html="question.content" class="question-text"></div>
                <div class="student-answer">
                  <p class="answer-label">学生答案：</p>
                  <div v-html="question.studentAnswer" class="answer-content"></div>
                </div>
                <div class="marking-area">
                  <div class="score-input">
                    <span>得分：</span>
                    <el-input-number 
                      v-model="question.givenScore" 
                      :min="0" 
                      :max="question.score" 
                      :step="0.5" 
                      size="small"
                    ></el-input-number>
                  </div>
                  <div class="comment-input">
                    <span>评语：</span>
                    <el-input 
                      v-model="question.comment" 
                      type="textarea" 
                      placeholder="请输入评语"
                      :rows="2"
                    ></el-input>
                  </div>
                </div>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
        
        <div class="total-score">
          <span>总分：{{ calculateTotalScore() }}/{{ paperTotalScore }}</span>
        </div>
      </el-card>
    </div>

    <!-- 按单道大题批阅模式 -->
    <div v-else-if="markingStrategy === 2" class="single-question-mode">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="question-selection">
            <template #header>
              <div class="selection-header">
                <span>批阅题目</span>
                <el-select v-model="currentQuestionGroup" placeholder="选择大题" size="small" @change="handleQuestionGroupChange">
                  <el-option 
                    v-for="(group, index) in paperContent" 
                    :key="index" 
                    :label="group.title" 
                    :value="index"
                  ></el-option>
                </el-select>
              </div>
            </template>
            <div class="student-list">
              <el-table :data="studentList" stripe style="width: 100%">
                <el-table-column prop="name" label="姓名" width="80"></el-table-column>
                <el-table-column prop="studentId" label="学号" width="100"></el-table-column>
                <el-table-column label="状态" width="80">
                  <template #default="scope">
                    <el-tag :type="scope.row.isMarked ? 'success' : 'info'">
                      {{ scope.row.isMarked ? '已批阅' : '未批阅' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="selectStudent(scope.row.id)"
                      :disabled="currentStudentId === scope.row.id"
                    >
                      批阅
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="18">
          <el-card v-if="currentStudentId" class="question-marking">
            <template #header>
              <div class="marking-header">
                <span>正在批阅：{{ selectedGroup?.title }} - {{ selectedStudent?.name }}</span>
              </div>
            </template>
            <div class="questions-container">
              <div v-for="(question, qIndex) in selectedGroupQuestions" :key="qIndex" class="question-marking-item">
                <div class="question-header">
                  <span class="question-title">{{ question.questionNum }}. {{ question.title }}</span>
                  <span class="question-score">({{ question.score }}分)</span>
                </div>
                <div class="question-content">
                  <div v-html="question.content" class="question-text"></div>
                  <div class="student-answer">
                    <p class="answer-label">学生答案：</p>
                    <div v-html="question.studentAnswer" class="answer-content"></div>
                  </div>
                  <div class="marking-area">
                    <div class="score-input">
                      <span>得分：</span>
                      <el-input-number 
                        v-model="question.givenScore" 
                        :min="0" 
                        :max="question.score" 
                        :step="0.5" 
                        size="small"
                      ></el-input-number>
                    </div>
                    <div class="comment-input">
                      <span>评语：</span>
                      <el-input 
                        v-model="question.comment" 
                        type="textarea" 
                        placeholder="请输入评语"
                        :rows="2"
                      ></el-input>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="marking-actions">
                <el-button type="success" @click="markNext">保存并批阅下一份</el-button>
                <el-button @click="saveCurrentMarking">仅保存当前批阅</el-button>
              </div>
            </div>
          </el-card>
          
          <el-empty v-else description="请从左侧选择学生进行批阅"></el-empty>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 批阅策略: 1-按整张试卷，2-按单道大题
const markingStrategy = ref(1)

// 模拟考试信息
const examInfo = ref({
  id: 'exam001',
  name: '2023年高等数学期末考试',
  startTime: '2023-06-10 09:00',
  endTime: '2023-06-10 11:00',
})

// 模拟试卷内容
const paperContent = ref([
  {
    id: 'group1',
    title: '一、选择题',
    questions: [
      {
        id: 'q1',
        questionNum: '1',
        title: '单选题',
        content: '已知函数f(x)=x²+2x+1，则f(0)的值为？',
        score: 5,
        studentAnswer: 'C. 1',
        givenScore: 0,
        comment: ''
      },
      {
        id: 'q2',
        questionNum: '2',
        title: '单选题',
        content: '下列哪个不是导数的基本公式？',
        score: 5,
        studentAnswer: 'B. (sinx)\'=cosx',
        givenScore: 0,
        comment: ''
      }
    ]
  },
  {
    id: 'group2',
    title: '二、填空题',
    questions: [
      {
        id: 'q3',
        questionNum: '3',
        title: '填空题',
        content: '函数f(x)=ln(x²+1)的导数是______。',
        score: 10,
        studentAnswer: 'f\'(x)=2x/(x²+1)',
        givenScore: 0,
        comment: ''
      }
    ]
  },
  {
    id: 'group3',
    title: '三、解答题',
    questions: [
      {
        id: 'q4',
        questionNum: '4',
        title: '解答题',
        content: '求函数f(x)=x³-3x²+3x-1的极值点及极值。',
        score: 20,
        studentAnswer: '解：f\'(x)=3x²-6x+3\nf\'(x)=3(x²-2x+1)=3(x-1)²\n当x=1时，f\'(x)=0\n又f\'\'(x)=6(x-1)>0 (当x>1时)\nf\'\'(1)=0\n需要求高阶导数\nf\'\'\'(x)=6>0\n所以当x=1时，f(x)取得极小值\nf(1)=1-3+3-1=0\n所以极小值为0',
        givenScore: 0,
        comment: ''
      }
    ]
  }
])

// 模拟学生列表
const studentList = ref([
  { id: 's1', name: '张三', studentId: '20230101', className: '计算机科学1班', submitTime: '2023-06-10 10:45', isMarked: false },
  { id: 's2', name: '李四', studentId: '20230102', className: '计算机科学1班', submitTime: '2023-06-10 10:50', isMarked: false },
  { id: 's3', name: '王五', studentId: '20230103', className: '计算机科学2班', submitTime: '2023-06-10 10:55', isMarked: false },
  { id: 's4', name: '赵六', studentId: '20230104', className: '计算机科学2班', submitTime: '2023-06-10 10:58', isMarked: false },
])

// 当前批阅的试卷索引（按整张试卷模式）
const currentPaperIndex = ref(0)
const totalPapers = computed(() => studentList.value.length)
const currentStudent = computed(() => studentList.value[currentPaperIndex.value] || {})

// 当前展开的题目组
const activeQuestionGroups = ref([0])

// 按题目批阅模式的状态
const currentQuestionGroup = ref(0)
const currentStudentId = ref('')

// 试卷总分
const paperTotalScore = computed(() => {
  return paperContent.value.reduce((total, group) => {
    return total + group.questions.reduce((groupTotal, q) => groupTotal + q.score, 0)
  }, 0)
})

// 计算当前学生的总分
const calculateTotalScore = () => {
  return paperContent.value.reduce((total, group) => {
    return total + group.questions.reduce((groupTotal, q) => groupTotal + (q.givenScore || 0), 0)
  }, 0)
}

// 当前选中的题目组
const selectedGroup = computed(() => {
  return paperContent.value[currentQuestionGroup.value]
})

// 当前选中的学生
const selectedStudent = computed(() => {
  return studentList.value.find(s => s.id === currentStudentId.value)
})

// 当前选中题目组的问题列表
const selectedGroupQuestions = computed(() => {
  if (!selectedGroup.value) return []
  return selectedGroup.value.questions
})

// 切换批阅策略
const handleStrategyChange = () => {
  activeQuestionGroups.value = [0]
  currentStudentId.value = ''
}

// 按整张试卷模式 - 上一份试卷
const prevPaper = () => {
  if (currentPaperIndex.value > 0) {
    currentPaperIndex.value--
  } else {
    ElMessage.warning('已经是第一份试卷')
  }
}

// 按整张试卷模式 - 下一份试卷
const nextPaper = () => {
  if (currentPaperIndex.value < totalPapers.value - 1) {
    currentPaperIndex.value++
  } else {
    ElMessage.warning('已经是最后一份试卷')
  }
}

// 按单道大题模式 - 选择题目组
const handleQuestionGroupChange = () => {
  // 切换题目组时重置当前学生
  currentStudentId.value = ''
}

// 按单道大题模式 - 选择学生
const selectStudent = (studentId) => {
  currentStudentId.value = studentId
}

// 按单道大题模式 - 保存并批阅下一个学生
const markNext = () => {
  saveCurrentMarking()
  
  // 找到下一个未批阅的学生
  const currentIndex = studentList.value.findIndex(s => s.id === currentStudentId.value)
  if (currentIndex >= 0 && currentIndex < studentList.value.length - 1) {
    currentStudentId.value = studentList.value[currentIndex + 1].id
  } else {
    ElMessage.success('已完成当前题目的所有学生批阅')
    currentStudentId.value = ''
  }
}

// 保存当前批阅结果
const saveCurrentMarking = () => {
  // 在实际应用中，这里应该调用API保存批阅结果
  if (markingStrategy.value === 2 && currentStudentId.value) {
    const student = studentList.value.find(s => s.id === currentStudentId.value)
    if (student) {
      student.isMarked = true
      ElMessage.success(`已保存 ${student.name} 的批阅结果`)
    }
  }
}

// 保存所有批阅结果
const saveMarking = () => {
  // 在实际应用中，这里应该调用API保存所有批阅结果
  if (markingStrategy.value === 1) {
    studentList.value[currentPaperIndex.value].isMarked = true
  }
  
  ElMessage.success('批阅结果已保存')
}

// 组件挂载时初始化
onMounted(() => {
  // 实际应用中，这里应该调用API获取考试信息、试卷内容和学生列表
})
</script>

<style scoped>
.marking-container {
  padding: 20px;
}

.marking-header {
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.header-title h2 {
  margin: 0;
  margin-right: 15px;
}

.header-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.marking-actions {
  display: flex;
  gap: 15px;
}

.student-info-card {
  margin-bottom: 20px;
}

.student-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.paper-counter {
  margin: 0 10px;
}

.question-item {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.question-header {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.question-title {
  font-weight: bold;
  margin-right: 8px;
}

.question-score {
  color: #ff6b6b;
}

.student-answer {
  background-color: #f8f9fa;
  padding: 10px;
  margin: 10px 0;
  border-radius: 4px;
}

.answer-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.marking-area {
  display: flex;
  flex-direction: column;
  gap: 10px;
  margin-top: 15px;
}

.score-input, .comment-input {
  display: flex;
  align-items: start;
  gap: 10px;
}

.score-input span, .comment-input span {
  width: 50px;
}

.total-score {
  text-align: right;
  margin-top: 20px;
  font-size: 18px;
  font-weight: bold;
}

/* 按单道大题批阅模式样式 */
.question-selection {
  height: calc(100vh - 200px);
  overflow: auto;
}

.selection-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.student-list {
  margin-top: 10px;
}

.question-marking {
  height: calc(100vh - 200px);
  overflow: auto;
}

.questions-container {
  padding-bottom: 60px;
}

.question-marking-item {
  margin-bottom: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
}

.marking-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
